# -*- coding:utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
import re
from com.mat.rpa.dao.projectAppDao import myAppDao

class DisplayLabel(QLabel):
    #设置类属性，所有对象共享，不用重复创建
    __font = QFont()
    __font.setPixelSize(20)
    __font.setBold(True)
    __metrics = QFontMetrics(__font)

    def __init__(self, parent=None):
        super(DisplayLabel, self).__init__(parent)
        self.setMaximumHeight(40)

    def setAutoWidthText(self, text):
        self.setFont(DisplayLabel.__font)
        self.setText(text)
        self.setMaximumWidth(DisplayLabel.__metrics.boundingRect(text).size().width()*1.4+18)

class AppTablePanel(QWidget):
    picPath = "./com/mat/rpa/views/projectWindow/mainWindow/mainPanel/btnAndTablePanel/images/"
    def __init__(self, parent=None):
        super(AppTablePanel, self).__init__(parent)
        self.parentPanel = parent
        #数据模型
        self.model = None
        #数据表
        self.tableView = None
        #总页数文本
        self.totalPageLabel = None
        #当前页文本
        self.currentPageLabel = None
        #转到页输入框
        self.switchPageLineEdit = None
        #前一页按钮
        self.prevButton = None
        #后一页按钮
        self.nextButton = None
        #转到页按钮
        self.switchPageButton = None
        #当前页
        self.currentPage = 0
        #总页数
        self.totalPage = 0
        #总记录数
        self.totalRecordCount = 0
        #每页显示记录数
        self.pageRecordCount = 10
        self.initUI()

    def initDB(self):
        self.myAppDaoObj = myAppDao.MyAppDao(self)
        # 设置当前页
        self.currentPage = 1
        # 得到总记录数
        self.myAppDaoObj.queryTotalRecordCount()
        # 查询第0页记录
        self.myAppDaoObj.queryLimitedAppsIntoTable(0, self.pageRecordCount)
        # #插入一条记录
        # self.myAppDao.insertIntoOneRecord(("应用程序3", "2021-12-31", 1))
        # self.myAppDao.delRecordByAppName("应用程序3")

    def initUI(self):
        # 创建窗口
        self.createWindow()
        #设置表格
        self.setTableView()
        self.updateStatus(0)
        #初始化数据库
        self.initDB()
        # 信号槽连接
        self.prevButton.clicked.connect(self.onPrevButtonClick)
        self.nextButton.clicked.connect(self.onNextButtonClick)
        self.switchPageButton.clicked.connect(self.onSwitchPageButtonClick)
        self.myAppDaoObj.queryLimitedAppSignal.connect(self.insertAppRecordIntoTableWidget)

    def createWindow(self):
        #操作布局
        operatorLayout= QHBoxLayout()
        operatorLayout.setContentsMargins(0,0,5,0)
        operatorLayout.setSpacing(5)
        self.prevButton = QPushButton("前一页")
        self.nextButton = QPushButton("后一页")
        self.switchPageButton = QPushButton("Go")
        self.switchPageLineEdit = QLineEdit()
        self.switchPageLineEdit.setFixedWidth(40)
        switchPage = QLabel("转到第")
        page = QLabel("页")
        operatorLayout.addWidget(self.prevButton)
        operatorLayout.addWidget(self.nextButton)
        operatorLayout.addWidget(switchPage)
        operatorLayout.addWidget(self.switchPageLineEdit)
        operatorLayout.addWidget(page)
        operatorLayout.addWidget(self.switchPageButton)
        operatorLayout.addStretch(1)
        #设置表格属性
        self.tableWidget = QTableWidget()
        self.totalPageLabel = DisplayLabel()
        self.currentPageLabel = DisplayLabel()
        self.totalRecordLabel = DisplayLabel()
        operatorLayout.addWidget(self.totalPageLabel)
        operatorLayout.addWidget(self.currentPageLabel)
        operatorLayout.addWidget(self.totalRecordLabel)
        #创建分页控件的主窗口
        mainLayout = QVBoxLayout(self)
        mainLayout.setContentsMargins(5,0,5,5)
        mainLayout.setSpacing(0)
        mainLayout.addWidget(self.tableWidget)
        mainLayout.addLayout(operatorLayout)
        self.setLayout(mainLayout)

    def setTableView(self):
        #设置表格头
        self.title = ['应用名称', '更新时间', '状态', '']
        # 创建模型
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setHorizontalHeaderLabels(self.title)
        headerView = self.tableWidget.horizontalHeader()
        headerView.setDefaultAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        #设置表格各列宽度
        desktop = QApplication.desktop()
        # 得到屏幕可显示尺寸
        rect = desktop.availableGeometry()
        screenWidth = rect.width()
        self.tableWidth = screenWidth*0.78
        self.tableWidget.setColumnWidth(0, self.tableWidth*0.5)
        self.tableWidget.setColumnWidth(1, self.tableWidth*0.2)
        self.tableWidget.setColumnWidth(2, self.tableWidth*0.1)
        self.tableWidget.setColumnWidth(3, self.tableWidth*0.2)
        self.tableWidget.verticalHeader().setVisible(False)
        # 设置各行高度
        self.tableWidget.verticalHeader().setDefaultSectionSize(60)
        #去除表格线
        self.tableWidget.setShowGrid(False)
        # self.tableWidget.setFocusPolicy(Qt.NoFocus)
        #让按钮小一些
        self.tableWidget.setStyleSheet('''
        QTableView::item {
            padding: 5;
            border-bottom: 1px solid #CCC;
        }
        QTableView::item:selected {
            background-color: #FAF0F0;
            color: black;
        }
        QTableWidget {
            outline: none;
        }
        QHeaderView::section {
            color: #444;
            padding: 5px;
            border-style: none;
            background-color: #e5e5e5
        }
        ''')

    # 刷新状态
    def updateStatus(self, totalRecordCount):
        szCurrentText = ("当前第%d页" % self.currentPage)
        self.currentPageLabel.setAutoWidthText(szCurrentText)
        self.setTotalRecordLabel(totalRecordCount)
        self.getPageCount()
        self.setTotalPageLabel()

        # 设置按钮是否可用
        if self.currentPage == 1:
            self.prevButton.setEnabled(False)
            self.nextButton.setEnabled(True)
        elif self.currentPage == self.totalPage:
            self.prevButton.setEnabled(True)
            self.nextButton.setEnabled(False)
        else:
            self.prevButton.setEnabled(True)
            self.nextButton.setEnabled(True)

    def addBtnToTableCell(self, row):
        btnPanel = QWidget()
        btnPanelLayout = QHBoxLayout()
        btnPanel.setLayout(btnPanelLayout)
        btnPanelLayout.setContentsMargins(0,0,0,0)
        btnPanelLayout.setSpacing(5)
        runBtn = QPushButton()
        runBtn.setIcon(QIcon(QPixmap(AppTablePanel.picPath + "runBtn.png")))
        btnPanelLayout.addWidget(runBtn)
        editBtn = QPushButton()
        editBtn.setIcon(QIcon(QPixmap(AppTablePanel.picPath + "editBtn.png")))
        btnPanelLayout.addWidget(editBtn)
        infoBtn = QPushButton()
        infoBtn.setIcon(QIcon(QPixmap(AppTablePanel.picPath + "infoBtn.png")))
        btnPanelLayout.addWidget(infoBtn)
        ellipsisBtn = QPushButton()
        ellipsisBtn.setIcon(QIcon(QPixmap(AppTablePanel.picPath + "ellipsisBtn.png")))
        btnPanelLayout.addWidget(ellipsisBtn)
        self.tableWidget.setCellWidget(row, 3, btnPanel)

    def insertAppRecordIntoTableWidget(self, rowCount, resultTuple):
        print("获得的rowCount为", rowCount)
        self.tableWidget.setRowCount(rowCount)
        for row, linedata in enumerate(resultTuple):
            for col, itemdata in enumerate(linedata):
                if col not in [0, 1]:
                    #第0列是自增，不要，而从后边重新计算,第一列表示分类
                    #0:表示属于我创建的应用
                    #1:表示回收站的应用
                    #2:表示获取的应用
                    item = QTableWidgetItem(str(itemdata)) if itemdata != None else QTableWidgetItem('')
                    if col == 2:
                        __font = QFont()
                        __font.setPixelSize(15)
                        item.setFont(__font)
                    else:
                        item.setForeground(QColor(68, 68, 68))
                    self.tableWidget.setItem(row, col - 2, item)
            self.addBtnToTableCell(row)
        self.tableWidget.update()

    # 得到页数
    def getPageCount(self):
        print(self.totalRecordCount, self.pageRecordCount)
        if (self.totalRecordCount % self.pageRecordCount) == 0:
            self.totalPage = (self.totalRecordCount // self.pageRecordCount)
        else:
            self.totalPage = (self.totalRecordCount // self.pageRecordCount+1)

    # 设置总数页文本
    def setTotalPageLabel(self):
        szPageCountText = ("总共%d页" % self.totalPage)
        self.totalPageLabel.setAutoWidthText(szPageCountText)

    # 设置总记录数
    def setTotalRecordLabel(self, totalRecordCount):
        self.totalRecordCount = totalRecordCount
        szTotalRecordText = ("共%d条" % self.totalRecordCount)
        self.totalRecordLabel.setAutoWidthText(szTotalRecordText)

    #前一页按钮对应的槽函数
    def onPrevButtonClick(self):
        self.currentPage = 1 \
            if self.currentPage<1 else self.currentPage-1
        limitIndex = (self.currentPage-1)*self.pageRecordCount
        self.recordQuery(limitIndex)
        self.updateStatus()

    #后一页按钮对应的槽函数
    def onNextButtonClick(self):
        self.currentPage = self.totalPage \
            if self.currentPage>self.totalPage else self.currentPage+1
        limitIndex = (self.currentPage-1)*self.pageRecordCount
        self.recordQuery(limitIndex)
        self.updateStatus()

    # 转到页按钮按下
    def onSwitchPageButtonClick(self):
        # 得到输入字符串
        szText = self.switchPageLineEdit.text()
        # 数字正则表达式
        pattern = re.compile(r'^[-+]?[0-9]+$')
        match = pattern.match(szText)
        # 判断是否为数字
        if not match:
            QMessageBox.information(self,
                            "提示", "请输入数字")
            return
        # 是否为空
        if szText == '':
            QMessageBox.information(self,
                            "提示", "请输入跳转页面")
            return
        # 得到页数
        pageIndex = int(szText)
        # 判断是否有指定页
        if pageIndex > self.totalPage or pageIndex < 1:
            QMessageBox.information(self,
                    "提示", "没有指定的页面，请重新输入")
            return
        # 得到查询起始行号
        limitIndex = (pageIndex - 1) * self.pageRecordCount
        # 记录查询
        self.recordQuery(limitIndex)
        # 设置当前页
        self.currentPage = pageIndex
        # 刷新状态
        self.updateStatus()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 创建窗口
    example = AppTablePanel()
    # 显示窗口
    example.show()
    sys.exit(app.exec_())